package org.noote.libs.virtualpad;

public class VirtualTouchPad {

	public static int TOUCH_RELEASED = 0;
	public static int TOUCH_PRESSED = 1;
	public static int TOUCH_MOVED = 2;
	
	protected int _iMin_X=0, _iMin_Y=0;
	protected int _iMax_X=0, _iMax_Y=0;

	protected int _iState = 0;
	protected float _fPosition_X=0, _fPosition_Y=0;

	protected boolean _bNewEvent = false;
	protected int _iCurID = -1;
	
	protected int _iOldState = 0;
	protected float _fOldPosition_X=0, _fOldPosition_Y=0;

	public VirtualTouchPad()
	{		
	}

	public void setWorkSpace(int x, int y, int sx, int sy)
	{
		_iMin_X=x;
		_iMin_Y=y;
		_iMax_X=x+sx;
		_iMax_Y=y+sy;
	}

	public boolean isInWorkSpace(int x, int y)
	{
		if(x>=_iMin_X && x<=_iMax_X && y>=_iMin_Y && y<=_iMax_Y)
			return true;
			
		return false;
	}
	
	public void setTouchEvent(int x, int y, int id, int state)
	{
		// toujours dans l'espace de travail
		if(isInWorkSpace(x, y))
		{
			// this is not for this pressed button ?
			if(_iState == TOUCH_RELEASED)	_iCurID = id;
			else if(_iCurID != id)			return;
				
			// stock old state
			_iOldState = _iState;
			_fOldPosition_X = _fPosition_X;
			_fOldPosition_Y = _fPosition_Y;
			
			// new state
			_iState = state;

			// calcul touch position
			_fPosition_X = ((float)(_iMax_X-x)/(float)(_iMax_X-_iMin_X));
			_fPosition_Y = 1.0f-((float)(_iMax_Y-y)/(float)(_iMax_Y-_iMin_Y));
			_fPosition_X -=0.5f;
			_fPosition_Y -=0.5f;
			_fPosition_X *=2.0f;
			_fPosition_Y *=2.0f;		

			_checkButtons();
		}
		// out of workspace ?
		else if(_iCurID >-1 && _iCurID == id)
		{
			_iCurID = -1;
			if(_iState != TOUCH_RELEASED)
			{
				_iState = TOUCH_RELEASED;
				_bNewEvent = true;
			}
			
			_checkButtons();
		}
	}
	
	public void reset()
	{
		_bNewEvent = true;
		_fPosition_X =0;
		_fPosition_Y =0;
		_iState = TOUCH_RELEASED;
		_iCurID = -1;

		_checkButtons();		
	}
	
	protected void _checkButtons()
	{
		// each movement is a new event in analog :)
		_bNewEvent = true;
	}
	
	public boolean haveNewEvent(){return _bNewEvent;}
	public void resetNewEvent(){_bNewEvent = false;}
	
	public float getX(){return _fPosition_X;}
	public float getY(){return _fPosition_Y;}
	public float getTouch(){return _iState==TOUCH_RELEASED?0.0f:1.0f;}
}
